package io.gitee.zhangbinhub.acp.boot.component

import com.fasterxml.jackson.core.StreamReadConstraints
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.SerializationFeature
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
import org.springframework.boot.autoconfigure.jackson.JacksonProperties
import org.springframework.core.Ordered
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

class AcpJackson2ObjectMapperBuilderCustomizer(private val jacksonProperties: JacksonProperties) :
    Jackson2ObjectMapperBuilderCustomizer, Ordered {
    override fun customize(jacksonObjectMapperBuilder: Jackson2ObjectMapperBuilder) {
        if (jacksonProperties.serialization[SerializationFeature.INDENT_OUTPUT] != false) {
            jacksonObjectMapperBuilder.featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        }
        if (jacksonProperties.deserialization[DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS] != false) {
            jacksonObjectMapperBuilder.featuresToEnable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
        }
        if (jacksonProperties.deserialization[DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES] != true) {
            jacksonObjectMapperBuilder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
        }
        if (jacksonProperties.mapper[MapperFeature.USE_STD_BEAN_NAMING] != false) {
            jacksonObjectMapperBuilder.featuresToEnable(MapperFeature.USE_STD_BEAN_NAMING)
        }
        jacksonObjectMapperBuilder.postConfigurer { objectMapper ->
            objectMapper.factory.setStreamReadConstraints(StreamReadConstraints.builder().maxNestingDepth(2000).build())
        }
    }

    override fun getOrder(): Int = 1
}